package com.suning.app.snpaasadmin.util;


import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;


public class JsonUtil {

	protected static final Log logger = LogFactory.getLog(JsonUtil.class);

	private final static ObjectMapper mapper = new ObjectMapper();

	public static Map<String, Object> convertJsonToMap(String json) {
		Map<String, Object> retMap = new HashMap<String, Object>();
		if (json != null) {
			try {
				retMap = mapper.readValue(json, new TypeReference<Map<String, Object>>() {});
			} catch (IOException e) {
				logger.warn("Error while reading Java Map from JSON response: " + json, e);
			}
		}
		return retMap;
	}

	public static List<Map<String, Object>> convertJsonToList(String json) {
		List<Map<String, Object>> retList = new ArrayList<Map<String, Object>>();
		if (json != null) {
			try {
				retList = mapper.readValue(json, new TypeReference<List<Map<String, Object>>>() {});
			} catch (IOException e) {
				logger.warn("Error while reading Java List from JSON response: " + json, e);
			}
		}
		return retList;
	}

	public static String convertToJson(Object value) {
		if (mapper.canSerialize(value.getClass())) {
			try {
				return mapper.writeValueAsString(value);
			} catch (IOException e) {
				logger.warn("Error while serializing " + value + " to JSON", e);
				return null;
			}
		}
		else {
			throw new IllegalArgumentException("Value of type " + value.getClass().getName() +
					" can not be serialized to JSON.");
		}
	}
	
	  @SuppressWarnings("unchecked")
    public static <T> T jsonToBean(String jsonString, Class<T> beanCalss) {
	         
	        JSONObject jsonObject = JSONObject.fromObject(jsonString);
	        T bean = (T) JSONObject.toBean(jsonObject, beanCalss);
	         
	        return bean;
	         
	    }
	  /**  
	     * 从json对象集合表达式中得到一个java对象列表  
	     *
	     * @param jsonString  
	     * @param beanClass  
	     * @return  
	     */
	    @SuppressWarnings("unchecked")
	    public static <T> List<T> jsonToBeanList(String jsonString, Class<T> beanClass) {
	 
	        JSONArray jsonArray = JSONArray.fromObject(jsonString);
	        JSONObject jsonObject;
	        T bean;
	        int size = jsonArray.size();
	        List<T> list = new ArrayList<T>(size);
	 
	        for (int i = 0; i < size; i++) {
	 
	            jsonObject = jsonArray.getJSONObject(i);
	            bean = (T) JSONObject.toBean(jsonObject, beanClass);
	            list.add(bean);
	 
	        }
	         
	        return list;
	 
	    }
}
